package com.ray.database;

import com.alibaba.druid.pool.DruidDataSource;
import com.jfinal.plugin.activerecord.ActiveRecordPlugin;
import com.ray.model._MappingKit;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.jdbc.datasource.DataSourceTransactionManager;
import org.springframework.jdbc.datasource.TransactionAwareDataSourceProxy;

import java.sql.SQLException;

@Configuration
public class JfinalActiveRecordConfig {

    @Value("${spring.datasource.base.name}")
    private String base;

    @Value("${spring.datasource.sys.name}")
    private String sys;

    @Bean
    @ConfigurationProperties("spring.datasource.base")
    public DruidDataSource baseDatasource() throws SQLException {
        DruidDataSource dataSource = new DruidDataSource();
        dataSource.setFilters("stat");
        return dataSource;
    }

    @Bean
    @ConfigurationProperties("spring.datasource.sys")
    public DruidDataSource sysDatasource(){
        return new DruidDataSource();
    }

    @Bean
    public ActiveRecordPlugin initDase() throws SQLException {
        ActiveRecordPlugin arp = new ActiveRecordPlugin(base,baseProxy());
        _MappingKit.mapping(arp);
        arp.start();
        return arp;
    }

    @Bean
    public ActiveRecordPlugin initSys(DruidDataSource sysDatasource){
        ActiveRecordPlugin arp = new ActiveRecordPlugin(sys,sysDatasource);
        arp.start();
        return arp;
    }

    @Bean
    public TransactionAwareDataSourceProxy baseProxy() throws SQLException {
        TransactionAwareDataSourceProxy transactionAwareDataSourceProxy = new TransactionAwareDataSourceProxy();
        transactionAwareDataSourceProxy.setTargetDataSource(baseDatasource());
        return transactionAwareDataSourceProxy;
    }

    @Bean
    public DataSourceTransactionManager baseTransactionManager() throws SQLException {
        DataSourceTransactionManager dataSourceTransactionManager = new DataSourceTransactionManager();
        dataSourceTransactionManager.setDataSource(baseProxy());
        return dataSourceTransactionManager;
    }

}
